package com.ruoyi.framework.extendsions.web.sevice;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.extendsions.config.WechatAppConfig;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service("userPhoneCodeDetailsService")
public class UserPhoneCodeDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserPhoneCodeDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phoneNumber) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByPhonenumber(phoneNumber);
        if (StringUtils.isNull(user))
        {
            user = initNewUser(phoneNumber);
            user.getParams().put("add", true);
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录手机账户：{} 已被删除.", phoneNumber);
            throw new ServiceException("改手机号已被移除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录手机账户：{} 已被停用.", phoneNumber);
            throw new ServiceException("该手机账户已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }


    public SysUser initNewUser(String phoneNumber){
        SysUser sysUser = new SysUser();
        sysUser.setUserName(phoneNumber);
        sysUser.setNickName("@"+phoneNumber);
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        sysUser.setPhonenumber(phoneNumber);
        sysUser.setDeptId(WechatAppConfig.getApp().getDeptId());
        //
        boolean regFlag = userService.registerUser(sysUser);
        if (!regFlag)
        {
//            msg = "注册失败,请联系系统管理人员";
        }
        else {
            //自动添加规则

            userService.insertUserAuth(sysUser.getUserId(), WechatAppConfig.getApp().getRoleId());
        }
        return sysUser;
    }
}
